package com.whj.client;

import com.whj.common.serializer.JSONSerializer;
import com.whj.common.serializer.RpcDecoder;
import com.whj.common.serializer.RpcEncoder;
import com.whj.handler.ClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NettyClient {
    private static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    private static ClientHandler clientHandler;
    public static void initClient() throws Exception{
        clientHandler = new ClientHandler();
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new RpcEncoder(Object.class, new JSONSerializer()));
                        pipeline.addLast(new RpcDecoder(Object.class, new JSONSerializer()));
                        //添加自定义事件处理器
                        pipeline.addLast(clientHandler);
                    }
                });
        bootstrap.connect("127.0.0.1", 9527).sync();
    }

    /**
     * 生成代理对象
     * @param serviceClass
     * @return
     */
    public static Object createProxy(Class<?> serviceClass){
        return Proxy.newProxyInstance(
                Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass},
                new InvocationHandler() {
                    @Override
                    //原方法调用时执行：
                    /**
                     * @param args  serviceClass实例调用method方法的参数
                     * providerParam + args[0] 就是最终的前端请求协议！
                     */
                    public Object invoke(Object o, Method method, Object[] args) throws Throwable {
                        //1) 原方法一旦调用，就执行初始化客户端
                        if(clientHandler==null){
                            initClient();
                        }
                        //2) 给UserClientHandler设置param参数
                        clientHandler.setParam(args[0]);
                        //3) 使用线程池，开启一个线程池处理call()写操作，并返回结果
                        Object result = executorService.submit(clientHandler).get();//
                        //4) return 结果
                        return result;
                    }
                }
        );
    }
}
